
var GoogleFeed = new Class({
    Implements: Options,
    options: {
        'tagid':''
    },
    curPage: 0,
    vendorid: 0,
    categoryid: 0,
    appleid: 0,
    sortid: 0,
    orderby: 'ASC',
    userid: 0,
    holidayDate: null,
    initialize: function(opts) {
        this.setOptions(opts);

        this.panel = document.id(this.options.tagid);
        if(!this.panel) return;

        this.tier = document.id('tier');
        this.tier.empty();

        this.getVendors = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'get',
            onRequest: function() {
                new ShowBox().say('get Vendors...');
                new Loader().show();
            },
            onComplete: function(resp) {
                var data = [];
                try {
                    data = eval('(' + resp + ')');
                }
                catch(err) { alert('Error googleFeed\n' + err); return; }
                new Loader().hide();

                this.doVendorsSelect(data);
            }.bind(this)
        }).send('table=gfeed&ex=getVendors&nc=' + Date.now());

    },
    doVendorsSelect: function(data) {

        new Element('input#asku[size=13][maxlength=15][type=text][value=Accware SKU]', {
            'events': {
                'click': function(ev) {
                    ev.target.set('value', '');
                    this.focus();
                    this.select();
                }
            }
        }).inject(this.tier);

        this.vendorSelect = new Element('select[style=width:180px;]', {
            'events': {
                'change': function() {
                    var vendorid = this.vendorSelect.getElement(':selected').get('value');
                    if(vendorid === '0') {
                        this.usersSelect.set('disabled', 'disabled');
                    }
                    else {
                        this.usersSelect.erase('disabled');
                    }
                }.bind(this)
            }
        }).inject(this.tier);

        new Element('option[value=0][text=-= Select Vendor =-]').inject(this.vendorSelect);
        data.vends.sort(this.sort).each(function(vendor) {
            new Element('option[value=' +  vendor.vid + '][html=' + vendor.als + ': ' + vendor.name + ']').inject(this.vendorSelect);
        }.bind(this));

        this.usersSelect = new Element('select[style=width:120px;][disabled=disabled]').inject(this.tier);
        new Element('option[value=0][text=-= Select User =-]').inject(this.usersSelect);
        data.users.sort(this.sort).each(function(user) {
            new Element('option[value=' +  user.uid + '][text=' + user.name + ']').inject(this.usersSelect);
        }.bind(this));

        this.appleSelect = new Element('select[style=width:120px;]').inject(this.tier);
        new Element('option[value=0][text=-= Filter Oldest =-]').inject(this.appleSelect);
        ['0 - 30 days', '31 - 60 days', '61 - 90 days', '91 - 180 days', '181 - 240 days', '241 - more days', 'not defined'].each(function(apple, idx) {
            new Element('option.applesl' + idx + '[value=' + (idx + 1) + '][text=' + apple + ']').inject(this.appleSelect);
        }.bind(this));

        new Element('button[style=color:red;font-weight:bold;][text=GO]',{
            'events': {
                'click': this.loadItems.bind(this),
                'focus': function() {this.blur();}
            }
        }).inject(this.tier);

        var buttonWeekly = new Element('button[text=START][style=font-weight:bold;color:red;padding:1px 2px;]',{
            'events': {
                'click': this.weekly.bind(this),
                'focus': function() {this.blur();}
            }
        });

        new Element('span[style=padding-left:50px;]').adopt(
            new Element('b[html=Weekly Discount :&nbsp;&nbsp;]'),
            buttonWeekly,
            new Element('span#loader[style=background:transparent url(../webstat/img/loader-big.gif) no-repeat scroll 0 0;]')
      ).inject(this.tier);

        this.holidayPercentSelect = new Element('select[style=width:65px;]');
        new Element('option[value=0][text=Percent]').inject(this.holidayPercentSelect);
        [1,2,3,4,5,7.5,10,12,15,20].each(function(percent) {
            new Element('option[value=' +  percent + '][text=' + percent + '%]').inject(this.holidayPercentSelect);
        }.bind(this));

        var buttonHoliday = new Element('button[text=START][style=font-weight:bold;color:red;padding:1px 2px;]',{
            'events': {
                'click': this.holidayStart.bind(this),
                'focus': function() {this.blur();}
            }
        });
        var buttonBackup = new Element('button[text=BACKUP][style=font-weight:bold;color:green;padding:1px 2px;]',{
            'events': {
                'click': this.holidayBackup.bind(this),
                'focus': function() {this.blur();}
            }
        });

        new Element('span[style=padding-left:50px;]').adopt(
            new Element('b[html=Holiday Discount :&nbsp;&nbsp;]'),
            this.holidayPercentSelect,
            buttonHoliday,
            buttonBackup
        ).inject(this.tier);

        var buttonStatus = new Element('button[text=STATUS][style=font-weight:bold;color:blue;padding:1px 2px;]',{
            'events': {
                'click': this.status.bind(this),
                'focus': function() {this.blur();}
            }
        });
        new Element('span[style=padding-left:50px;]').adopt(
            buttonStatus
        ).inject(this.tier);

        this.divData = new Element('div#data');
        this.divData.inject(this.tier, 'bottom');
    },
    holidayStart: function(ev) {
        ev.stop();

        var percent = this.holidayPercentSelect.getElement(':selected').get('value');
        if(percent === 0) {
            alert("Select percent!");
            return;
        }

        var r = confirm("Сейчас запуститься программа update Holyday Discount " + percent + "%\nУверен что хочешь этого?");
        if(r !== true) {
            alert("You pressed Cancel!");
            return;
        }

        window.location.href = '/GoogleFeed/googleservice?exec=holiday&percent=' + this.holidayPercentSelect.getElement(':selected').get('value') + '&nc=' + Date.now();
    },
    status: function(ev) {
        ev.stop();

        this.getVendors = new Request({
            url: '/Admin/webstat/httpservice',
            onRequest: function() {
                new ShowBox().say('get Status...');
                new Loader().show();
            },
            onComplete: function(resp) {
                var data = [];
                try {
                    data = eval('(' + resp + ')');
                }
                catch(err) { alert('Error...\n' + err); return; }
                new Loader().hide();

                this.showStatus(data);
            }.bind(this)
        }).send('table=util&ex=getStatus&nc=' + Date.now());

    },
    showStatus: function(data) {

        //make body
        var tbody = new Element('tbody'), count = 0;
        data.status.each(function(site) {
            count += site.cnt;
            tbody.adopt(
                new Element('tr.left').adopt(new Element('th[html=&nbsp;&nbsp;&nbsp;' + site.name + ']'), new Element('td[text=' + site.cnt + ']'))
            );
        });

        tbody.adopt(
            new Element('tr').adopt(new Element('td[colspan=2][html=<hr/>]')),
            new Element('tr').adopt(
                new Element('th.left[html=&nbsp;&nbsp;&nbsp;Total]'),
                new Element('td[text=' + count + ']')
            )
        );

        new ModalBox({
            width: 300,
            modal: {
                background: '#555'
            },
            onOpen: function() {
            }.bind(this)
        }).doBox('<h2>Status</h2>', new Element('center').adopt(new Element('table#ggroup[width=100%]').adopt(tbody)));

    },
    holidayBackup: function(ev) {
        ev.stop();

        window.location.href = '/GoogleFeed/googleservice?exec=backup&nc=' + Date.now();
    },
    weekly: function(ev) {
        ev.stop();

        var r = confirm("Сейчас запуститься программа update to froogle\nУверен что хочешь этого?");
        if(r !== true) {
            alert("You pressed Cancel!");
            return;
        }

        window.location.href = '/GoogleFeed/googleservice?exec=weekly&nc=' + Date.now();

    },
    loadItems: function(ev) {

        ev.stop();
        this.divData.empty();

        this.categoryid = 0;
        this.vendorid = this.vendorSelect.getElement(':selected').get('value');
        this.userid = this.usersSelect.getElement(':selected').get('value');
        this.appleid = this.appleSelect.getElement(':selected').get('value');
        this.accwareSKU = document.id('asku').get('value');

        if(this.vendorid === 0 && (this.accwareSKU === 'Accware SKU' || this.accwareSKU === '')) {
            alert('Please select Accware SKU or Vendor or User');
            return;
        }

        var pager = new Element('td.right');
        var ptab = new Element('table#pager').adopt(
            new Element('tbody').adopt(
                new Element('tr').adopt(
                    new Element('td.left[html=&nbsp;]'),
                    pager
                )
            )
        );

        this.pager = new Pager({
            'tagid': pager,
            'onNewpage': function(currentPage) {
                this.curPage = currentPage;

                this.openItemsRequest.send(
                    'table=gfeed&ex=getItems&vid=' + this.vendorid +
                    '&uid=' + this.userid +
                    '&cid=' + this.categoryid +
                    '&aid=' + this.appleid +
                    '&curPage=' + this.curPage +
                    '&srt=' + this.sortid +
                    '&drt=' + this.orderby +
                    '&nc=' + Date.now());
            }.bind(this)
        });

        this.itemData = new Element('table#listData[rules=groups]');

        this.categoryTag = new Element('div#catMenu');
        var table = new Element('table[style=width:100%;]').adopt(
            new Element('tbody').adopt(
                new Element('tr').adopt(
                    new Element('td[style=width:200px;min-width:200px;vertical-align:top;]').adopt(
                        this.categoryTag
                    ),
                    new Element('td[style=vertical-align:top;]').adopt(
                        this.itemData
                    )
                )
            )
        );

        this.menu = new CategoryMenu({
            'tagid': this.categoryTag,
            'onNewcategory': function(currentCategoryID) {
                this.categoryid = currentCategoryID;

                this.openItemsRequest.send('table=gfeed&ex=getItems&curPage=0&vid=' + this.vendorid + '&uid=' + this.userid + '&cid=' + this.categoryid + '&aid=' + this.appleid + '&nc=' + Date.now());
            }.bind(this)
        });

        this.divData.adopt(
            new Element('div').adopt(ptab, table)
        );

        var params = 'table=gfeed&ex=getItems&curPage=0&vid=' + this.vendorid + '&uid=' + this.userid + '&cid=' + this.categoryid + '&aid=' + this.appleid;
        if(this.vendorid === 0 && (this.accwareSKU !== 'Accware SKU' || this.accwareSKU !== '')) {
            params = 'table=gfeed&ex=getItemsSKU&sku=' + this.accwareSKU;
        }
        this.openItemsRequest = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'get',
            onRequest: function() {
                new ShowBox().say('Opening...');
                new Loader().show();
            },
            onComplete: function(resp) {
                var items = '';
                try {
                    items = eval('(' + resp + ')');
                }
                catch(err) { alert('Error...\n' + err); return; }
                new Loader().hide();

                this.showItems(items);
            }.bind(this)
        }).send(params + '&nc=' + Date.now());

    },
    showItems: function(items) {

        this.pager.setData(this.curPage, items.cntPage, items.onPage, items.rows.length);
        this.menu.setMenuData(items.cats);

        var tbody = new Element('tbody'), tr, color=false, tdo, priceTag;
        this.itemData.empty().adopt(
            new Element('thead').adopt(
                new Element('tr').adopt(
                    new Element('th.imgCol[html=&nbsp;]'),
                    new Element('th.brdCol.w50[text=SKU][style=cursor:pointer;]', {
                        'events':{
                            'mouseenter': function() { this.addClass('thHover'); },
                            'mouseleave': function() { this.removeClass('thHover'); },
                            'click': this.lastUpdateSort.bind(this, 'ac')
                        }
                    }),
                    new Element('th.brdCol.w50[text=MfrNumber][style=cursor:pointer;]', {
                        'events':{
                            'mouseenter': function() { this.addClass('thHover'); },
                            'mouseleave': function() { this.removeClass('thHover'); },
                            'click': this.lastUpdateSort.bind(this, 'mn')
                        }
                    }),
                    new Element('th.brdCol.w80[text=Name]'),
                    new Element('th.brdCol.w50[text=Cost Price][style=cursor:pointer;]'),
                    new Element('th.brdCol.w50[text=Resl Price][style=cursor:pointer;]', {
                        'events':{
                            'mouseenter': function() { this.addClass('thHover'); },
                            'mouseleave': function() { this.removeClass('thHover'); },
                            'click': this.lastUpdateSort.bind(this, 'rp')
                        }
                    }),
                    new Element('th.brdCol.w50[text=Sell Price][style=cursor:pointer;]', {
                        'events':{
                            'mouseenter': function() { this.addClass('thHover'); },
                            'mouseleave': function() { this.removeClass('thHover'); },
                            'click': this.lastUpdateSort.bind(this, 'sp')
                        }
                    }),
                    new Element('th.brdCol.w15[text=Stock]'),
                    new Element('th.brdCol.w15[text=Qty][style=cursor:pointer;]', {
                        'events':{
                            'mouseenter': function() { this.addClass('thHover'); },
                            'mouseleave': function() { this.removeClass('thHover'); },
                            'click': this.lastUpdateSort.bind(this, 'qt')
                        }
                    }),
                    new Element('th.brdCol.w50[text=Last Update][style=cursor:pointer;]', {
                        'events':{
                            'mouseenter': function() { this.addClass('thHover'); },
                            'mouseleave': function() { this.removeClass('thHover'); },
                            'click': this.lastUpdateSort.bind(this, 'lu')
                        }
                    })
                )
            ),
            new Element('tfoot').adopt(
                new Element('tr').adopt(
                    new Element('th.tdFull[colspan=10][html=&nbsp;]')
                )
            ),
            tbody
        );

        var tagid,title,lastUpdate;
        items.rows.each(function(item, idx) {

            tr = new Element('tr[style=background-color:' + (item.sellPrice > 5 ? ((color = !color) ? '#ffffff' : '#fcffcd') : 'silver') + ';]',{
                'events': {
                    'mouseenter': function() {this.addClass('rowHover');},
                    'mouseleave': function() {this.removeClass('rowHover');}
                }
            });

            tagid = 'ggl_' + idx;
            title = item.reason ? ' Google ' + item.reason + ' modification: ' + item.moddate.substring(0,10) + ' expare:' + item.expdate.substring(0,10) : ' sell price bellow $5';
            tdo = new Element('td.imgCol').adopt(
                new Element('a.plus[href=javascript:][html=&nbsp;][title=' + item.mfrNumber + title + ']',{
                    'events': {
                        'click': this.openGoogle.bind(this, tagid, item.mfrNumber, item.sellPrice),
                        'focus': function() {this.blur();}
                    }
                })
            );

            priceTag = new Element('td.brdCol.right.w50[text=$' + numberFormat(item.sellPrice) + '][style=cursor:pointer;font-weight:bold;]', {
                'events': {
                    'click': function(ev) {
                        ev.stop();

                        new ShowBox({
                            'onSave': function(accwareSKU, sellPrice, resPrice) {

                                this.savePrice(accwareSKU, sellPrice, resPrice);
                            }.bind(this),
                            onCancel: function() {
                            }
                        }).setPrice(ev);
                    }.bind(this),
                    'focus': function() {this.blur();}
                }
            });
            priceTag.store('accware', item.sku).store('selPrice', item.sellPrice).store('resPrice', item.hotPrice);

            if(item.hist) {
                lastUpdate = new Element('td.brdCol.center.w50[style=cursor:pointer;color:navy;][text=' + item.hist + ']',{
                    'events': {
                        'click': function(ev) {
                            ev.stop();

                            new ShowBox().getUserHistory(ev);

                        }.bind(this)
                    }
                });
                lastUpdate.store('iid', item.iid);
            }
            else {
                lastUpdate = new Element('td.brdCol.center.w50[html=&nbsp;]');
            }

            tbody.adopt(
                tr.adopt(
                    tdo,
                    new Element('td.imgCol.w50' + this.getApple(item.old) + '[html=&nbsp;&nbsp;&nbsp;' + item.sku + ']'),
                    new Element('td.brdCol.left.w50[text=' +  item.mfrNumber + ']'),
                    new Element('td.brdCol.left.w80[html=' + item.name  + ']'),
                    new Element('td.brdCol.right.w50[text=$' + numberFormat(item.costPrice) + ']'),
                    new Element('td.brdCol.right.w50[text=$' + numberFormat(item.hotPrice) + ']'),
                    priceTag,
                    new Element('td.brdCol.center.w15[text=' + (item.stock ? 'Y': 'N') + ']'),
                    new Element('td.brdCol.center.w15[text=' + (item.qty ? item.qty: '') + ']'),
                    lastUpdate
                )
            );

            tr = new Element('tr#x' + tagid + '[style=display:none;]').adopt(
                new Element('td[html=&nbsp;]'),
                new Element('td#d' + tagid + '[colspan=8][style=padding-top:0]')
            );
            tbody.adopt(tr);

        }, this);

    },
    lastUpdateSort: function(field) {

        this.orderby = (this.orderby === 'ASC') ? 'DESC' : 'ASC';
        switch(field) {
            case 'ac': this.sortid = 1; break;
            case 'mn': this.sortid = 2; break;
            case 'rp': this.sortid = 3; break;
            case 'sp': this.sortid = 4; break;
            case 'qt': this.sortid = 5; break;
            case 'lu': this.sortid = 6; break;
        }

        this.openItemsRequest.send(
            'table=gfeed&ex=getItems&vid=' + this.vendorid +
            '&uid=' + this.userid +
            '&cid=' + this.categoryid +
            '&aid=' + this.appleid +
            '&curPage=' + this.curPage +
            '&srt=' + this.sortid +
            '&drt=' + this.orderby +
            '&nc=' + Date.now());
    },
    openGoogle: function(tagid, mfrNumber, sellprice, ev) {

        var xcuc = document.id('x' + tagid);
        var dcuc = document.id('d' + tagid);
        if(ev.target.hasClass('plus')) {
            ev.target.removeClass('plus').addClass('minus').addClass('load');

            this.requestGoogle = new Request({
                url: '/GoogleFeed/googleservice',
                method: 'get',
                onRequest: function() {
                    new ShowBox().say('Connect to google...');
                },
                onComplete: function(resp) {
                    var gjson = "";
                    try {
                        gjson = eval('(' + resp + ')');
                    }
                    catch(err) { alert('Error...\n' + err); return; }
                    ev.target.removeClass('load');

                    this.showGoogleFeed(gjson, dcuc);
                }.bind(this)
            }).send('exec=search&query=' + mfrNumber + '&nc=' + Date.now());


            // if open orders not use hower
            xcuc.set('styles', {'display':'' ,'background-color':'#ffffff'});
        }
        else { // close block
            ev.target.removeClass('minus').addClass('plus');
            ev.target.getParent('tr').setStyle('opacity','0.3'); // set like visited
            xcuc.setStyle('display', 'none');
        }
    },
    showGoogleFeed: function(gjson, dcuc) {

        dcuc.empty();

        var feed = eval(gjson);
        if(!feed) return;

        var items = this.range(feed.items || []);
        if(!items.length) {
            dcuc.adopt(new Element('div[style=width:100%;color:red;font-size:16px;text-align:center;][text=Not find on google.]'));
            return;
        }

        var tbody = new Element('tbody');
        var thead = new Element('thead').adopt(
            new Element('tr').adopt(
                new Element('th[text=#]'),
                new Element('th[text=advert]'),
                new Element('th[text=name]'),
                new Element('th[text=brand]'),
                new Element('th[text=condition]'),
                new Element('th[text=price]')
            )
        );

        var priceTag, href, sku, dp, jdp, reslprice, sellprice, done;
        items.each(function(item, idx) {

            sellprice = item.product.inventories[0].price;

            if(item.product.author.accountId === '100115') {
 
                href = new URI(item.product.link);
                sku = href.getData('sku');
                dp = href.getData('dp');
                jdp = this.getDP(dp);
                reslprice = jdp.resPrice === '0' ? sellprice.toFloat() : jdp.resPrice.toFloat() / 100;

                priceTag = new Element('td.brdCol.right.w50[text=$' + numberFormat(sellprice) + '][style=cursor:pointer;font-weight:bold;]', {
                    'events': {
                        'click': function(ev) {
                            ev.stop();

                            new ShowBox({
                                'onSave': function(accwareSKU, selPrice, resPrice) {

                                    this.savePrice(accwareSKU, selPrice, resPrice);
                                }.bind(this),
                                onCancel: function() {
                                }
                            }).setPrice(ev);
                        }.bind(this),
                        'focus': function() {this.blur();}
                    }
                });
                priceTag.store('accware', sku).store('selPrice', sellprice).store('resPrice', reslprice);

                new Element('tr[style=background-color:silver;]').adopt(
                    new Element('td[text=' + (idx + 1) + ']'),
                    new Element('td' + this.getApple(jdp.oldest) + '[html=<div style="color:red;margin-left:30px;">' + sku + '</div><br/><b>' + 'Stock: ' + jdp.count + ', ' + jdp.vendor + '</b></div>]'),
                    new Element('td' + (jdp.drone === '1' ? '.drone' : '') + '[html=<div style="margin-left:30px;">' + item.product.title + '</div>]'),
                    new Element('td[text=' + item.product.brand + ']'),
                    new Element('td[text=' + item.product.condition + ']'),
                    new Element('td').adopt(priceTag)
                ).inject(tbody);
            }
            else {
                priceTag = new Element('b[text=$' + numberFormat(sellprice) + ']');

                new Element('tr').adopt(
                    new Element('td[text=' + (idx + 1) + ']'),
                    new Element('td[text=' + item.product.author.name + ']'),
                    //new Element('td[html=<a href="' + item.product.link + '">' + item.product.title + '</a>]'),
                    new Element('td').adopt(new Element('a.part[href=' + item.product.link + '][text=' + item.product.title + ']')),
                    new Element('td[text=' + item.product.brand + ']'),
                    new Element('td[text=' + item.product.condition + ']'),
                    new Element('td').adopt(priceTag)
                ).inject(tbody);
            }

        }, this);

        dcuc.adopt(new Element('table[border=1][style=width:100%;]').adopt(thead, tbody));

    },
    range: function(items) {
 
        var res = [];

        var compIdx = 0;
        items.each(function(item, idx) {
            if(item.product.author.accountId === '100115') {
                compIdx = idx;
            }
        });

        var end, window = 25;
        if(compIdx) {
            var beg = compIdx - window > 0 ? compIdx - window : 0;
            end = compIdx + window > items.length ? items.length : compIdx + window;

            for(var j= 0,i = beg; i < end; i++) {
                res[j++] = items[i];
            }
        }
        else {
            if(items.length) {
                end = items.length > window ? window : items.length;
                for(var i = 0; i < end; i++) {
                    res[i] = items[i];
                }
            }
        }

        return res;
    },
    savePrice: function(accwareSKU, selPrice, resPrice) {
        var userid =  window.sessionStorage.getItem('uid');
        if(!selPrice || !resPrice) {
            alert('Check price !');
            return;
        }
        if(!userid || userid === '0') {
            alert('Error: userid=' + userid + '\nNew version\nplease clean cookie 10.0.2.18\nand login again.\nThank you.');
            return;
        }
        this.requestGoogle = new Request({
            url: '/GoogleFeed/googleservice',
            method: 'get',
            onRequest: function() {
                new ShowBox().say('Save to google...');
                new Loader().show();
            },
            onComplete: function(resp) {
                new ShowBox().say(resp);
                new Loader().hide();
            }
        }).send('exec=changePrice&uid=' + userid + '&sku=' + accwareSKU + '&sprc=' + selPrice + '&rprc=' + resPrice + '&nc=' + Date.now());

    },
    sort: function(a, b) {
	return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
    },
    getDP: function(dp) {
        var keys = ['count', 'vendor', 'resPrice', 'drone', 'oldest'];
        var values = ['0', 'N/A', '0', '0', '0'];
        if(dp) {
            values = [];
            dp.split(':').each(function(itm) {
                values.push(itm);
            });
        }
        return values.associate(keys);
    },
    getApple: function(old) {
        var oldest = old.toInt();
        var apple = '';
        if(oldest === -1) apple = '';
        else if(0 >= oldest || oldest <= 30) apple = '.apple0';
        else if(31 >= oldest || oldest <= 60) apple = '.apple1';
        else if(61 >= oldest || oldest <= 90) apple = '.apple2';
        else if(91 >= oldest || oldest <= 180) apple = '.apple3';
        else if(181 >= oldest || oldest <= 240) apple = '.apple4';
        else apple = '.apple5';

        return apple;
    }
});
